package com.cdream.basic.java8.io.biochat;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @author cdream
 * @date 2022/8/16
 */
@Slf4j
public class ChatClient {
    private static final Integer PORT = 18080;
    private static final String HOST = "localhost";
    private static final String QUIT = "QUIT";

    public static void main(String[] args) {
        Socket socket = null;
        BufferedWriter bw = null;
        try {
            socket = new Socket(HOST, PORT);
            bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            // BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            // String consoleStr = console.readLine();
            // if (QUIT.equals(consoleStr)) {
            //     break;
            // }
            // bw.write(consoleStr+"\n");
            // bw.flush();
            // log.info("客户端发送：{}", consoleStr);
            String msg = null;
            BufferedWriter finalBw = bw;
            new Thread(() -> {
                handlerInput(finalBw);
            }).start();
            while ((msg = receiveMsg(br)) != null) {
                log.info("收到信息：{}", msg);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                    System.out.println("关闭socket");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @SneakyThrows
    public static void handlerInput(Writer bw) {
        while (true){
            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
            String consoleStr = console.readLine();
            bw.write(consoleStr+"\n");
            bw.flush();
            if (QUIT.equals(consoleStr)) {
                break;
            }
        }

    }

    @SneakyThrows
    public static String receiveMsg(BufferedReader br) {
        String serverStr = br.readLine();
        return serverStr;

    }

}
